<template>
	<div class="container">
		<h1 style="text-align: center;font-weight: bold;">工号计划汇总</h1>
		<a-form ref="formRef" :model="formState" layout="vertical" @finish="savePlan">
			<a-row :gutter="20">
				<a-col :span="24">
					<h3>计划信息</h3>
				</a-col>
				<a-col :span="12">
					<a-form-item label="选择项目" name="project_id" :rules="{ required: true, message: '请选择项目' }">
						<a-select v-model:value="formState.project_id" disabled :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" @change="changeProject"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="计划名称" name="name" :rules="{ required: true, message: '请输入计划名称' }">
						<a-input v-model:value="formState.name" disabled />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="计划编号" name="code" :rules="{ required: true, message: '请输入计划编号' }">
						<a-input v-model:value="formState.code" disabled />
					</a-form-item>
				</a-col>

				<a-col :span="12">
					<a-form-item label="计划制定人" name="opr_id" :rules="{ required: true, message: '请选择计划制定人' }">
						<a-select v-model:value="formState.user_id" disabled placeholder="请选择计划制定人" :options="userOptions" option-filter-prop="label"></a-select>
					</a-form-item>
				</a-col>

				<a-col :span="24">
					<h1 style="text-align: center;font-weight: bold;">物资计划清单</h1>
					<a-table :data-source="formState.materials" :scroll="tableScroll" :columns="planMaterialColumns" :row-key="(record) => record.key">
						<template #bodyCell="{ column, record, index }">
							<template v-if="column.dataIndex === 'name'">
								<a-form-item :name="['materials', index, 'source_id']" :rules="{ required: true, message: '请选择材料名称' }">
									<a-tree-select v-model:value="formState.materials[record.key].source_id" disabled placeholder="请选择材料名称" allow-clear tree-default-expand-all :tree-data="materialOptions" tree-node-filter-prop="label" style="width:100%" @change="(id) => changeMaterial(id, record)">
										<template #title="{ label }">{{ label }}</template>
									</a-tree-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'model'">
								<a-form-item :name="['materials', index, 'id']" :rules="{ required: true, message: '请选择规格' }">
									<a-select v-model:value="formState.materials[record.key].id" disabled placeholder="请选择" :options="materialModelOptions[record.source_id] || []" allow-clear :field-names="{ value: 'id', label: 'model' }" style="width:100%"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'unit'">
								<a-form-item :name="['materials', index, 'unit']" :rules="{ required: true, message: '请选择计量单位' }">
									<a-select v-model:value="formState.materials[record.key].unit" disabled placeholder="请选择" :options="unitOptions" :field-names="{ value: 'name' }" style="width:100%"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'quantity'">
								<a-form-item :name="['materials', index, 'quantity']" :rules="{ required: true, message: '请输入数量' }">
									<a-input v-model:value="formState.materials[index].quantity" disabled placeholder="请输入数量" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'gonghao'">
								<a-form-item :name="['materials', index, 'gonghao_' + column.extra]" :rules="{ required: true, message: '请输入数量' }">
									<a-input v-model:value="formState.materials[index]['gonghao_' + column.extra]" disabled placeholder="请输入数量" />
								</a-form-item>
							</template>
						</template>
					</a-table>
				</a-col>

				<a-col :span="24">
					<a-form-item label="备注" name="memo">
						<a-textarea v-model:value="formState.memo" disabled :auto-size="{ minRows: 4, maxRows: 6 }"></a-textarea>
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";

import dayjs from "dayjs";

import { post, listToTree } from "../utils";

import { useRoute } from "vue-router";
const route = useRoute();
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 680 }));
const id = computed(() => {
	return route.params.id || 0;
});

const formState = ref({ parent_id: route.query.parent_id || 0, materials: [] });
const projectOptions = ref([]);
const userOptions = ref([]);
onMounted(() => {
	const { parent_id } = formState.value;
	if (parent_id) {
		post("plan/info", { id: parent_id }).then(data => {
			const { name, code } = data;
			formState.value = {
				...formState.value,
				name,
				code
			};
		});
	} else if (id.value) {
		post("plan/info", { id: id.value }).then(data => {
			//data.user_ids = data.users.map(d => d.fullname) || [];
			data.user_id = data.opr_user.id;
			if (data.plan_date) data.plan_date = dayjs(data.plan_date);

			data.materials = data.materials.map((d, i) => {
				d.key = i;

				const { unit, quantity } = d.PlanMaterial;
				d.unit = unit;
				d.quantity = quantity;

				return d;
			});
			//构建工号
			post("department/info", { id: data.project_id }).then(d => {
				//获取工号
				pointData.value = d.pointData;
			});
			formState.value = data;
		});
	}

	post("user").then(({ data }) => {
		userOptions.value = data.map(d => {
			return {
				value: d.id,
				label: d.fullname || d.username
			};
		});
	});
	//projectOptions
	post("department/projects?type=3").then(({ data }) => {
		projectOptions.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});
	});
});
const pointData = ref([]);
const changeProject = value => {
	const project_id = value;
	post("department/info", { id: project_id }).then(data => {
		//自动生成计划编码
		if (data.name) {
			let py_name = "";
			const name = data.company_name + "-" + data.name;
			post("util/pinyin", { value: name }).then(res => {
				res.value.forEach(d => {
					py_name += d.toUpperCase();
				});
				//获取计划最大ID
				let maxid = 0;
				post("plan/maxid").then(max => {
					maxid = parseInt(max) + 1;
					formState.value.code = py_name + "-" + maxid;
				});
			});
		}
		//获取工号
		pointData.value = data.pointData;
	});
};

const { proxy } = getCurrentInstance();
const formRef = ref();
const savePlan = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			const params = { ...formState.value };
			if (!params.materials.length) {
				proxy.$message.error("请添加材料清单");
				return;
			}

			params.materials = JSON.stringify(params.materials);

			const { plan_date, user_ids = [] } = params;
			if (plan_date) params.plan_date = dayjs(plan_date).format("YYYY-MM-DD");
			params.user_ids = user_ids.join(",");

			post("plan/save", params)
				.then(() => {
					proxy.$message.success("信息提交成功", 1);

					closeTab("/plan");
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => { });
};
const planMaterialColumns = computed(() => {
	const planMaterialColumns = [
		{
			title: "ID",
			dataIndex: "key",
			width: 60,
			align: "center",
			extra: 0,
			customRender: ({ text, record, index, column }) => {
				return text + 1;
			}
		},
		{
			title: "材料名称",
			dataIndex: "name",
			width: 150,
			align: "center",
			extra: 0
		},
		{
			title: "材料规格",
			dataIndex: "model",
			width: 150,
			align: "center",
			extra: 0
		},
		{
			title: "单位",
			dataIndex: "unit",
			width: 150,
			extra: 0,
			align: "center"
		},
		{
			title: "数量",
			dataIndex: "quantity",
			width: 120,
			extra: 0,
			align: "center"
		}
	];
	pointData.value.forEach((p, i) => {
		planMaterialColumns.push({
			title: p.name,
			dataIndex: "gonghao",
			extra: p.id,
			width: 120,
			align: "center"
		});
	});

	return planMaterialColumns;
});

const unitOptions = ref([]);
post("dictionary", { root_code: "MATERIAL_UNIT" }).then(data => {
	unitOptions.value = data;
});

const materialOptions = ref([]);

post("dictionary", { root_code: "MATERIAL_CATEGORY" }).then(data => {
	const { root_id: rootId } = data[0] || {};
	materialOptions.value = listToTree(data, rootId);

	//获取所有规格
	post("material", { source_id: data.map(d => d.id).join(","), page_size: 10000 }).then(({ data }) => {
		materialModelOptions.value = (() => {
			const array = [];
			data.forEach(d => {
				if (!array[d.source_id]) array[d.source_id] = [];

				if (d.attr) d.model = `${d.model}（${d.attr}）`;

				array[d.source_id].push(d);
			});

			return array;
		})(data);
	});
});

const materialModelOptions = ref({});

const changeMaterial = (id, record) => {
	//强制选择规格
	record.id = null;

	if (!id) return;

	post("material", { source_id: id, page_size: 10000 }).then(({ data }) => {
		materialModelOptions.value[id] = data.map(d => {
			if (d.attr) d.model = `${d.model}（${d.attr}）`;

			return d;
		});
	});
};

//调用父页面closeTab方法
/*
//父页面定义closeTab方法
provide("closeTab", path => {
	
});
*/
const closeTab = inject("closeTab");
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;

	h2 {
		font-size: 16px;
		font-weight: 600;
		line-height: 30px;
		margin-bottom: 20px;
	}

	h3 {
		line-height: 40px;
		font-size: 16px;
		font-weight: 400;
		margin-bottom: 20px;

		display: flex;
		align-items: center;

		&:before {
			content: "";
			display: block;
			width: 2px;
			height: 20px;
			background: rgb(24, 144, 255);
			margin-right: 10px;
		}
	}

	h4 {
		font-weight: 600;
		margin: 15px 0;
		line-height: 30px;
	}
}

:deep(.ant-table-cell) .ant-form-item {
	margin-bottom: 0;

	.ant-form-item-explain {
		position: absolute;
		bottom: -24px;
	}
}

:deep(.ant-input[disabled]) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

:deep(.ant-input-disabled) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

//
:deep(.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

:deep(.ant-select-disabled.ant-select-multiple .ant-select-selection-item) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

:deep(.ant-picker-input > input[disabled]) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
}

:deep(.ant-picker.ant-picker-disabled) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
</style>
